(ns
  com.marzhillstudios.molehill.utils
  (:use [com.marzhillstudios.path]
        [com.marzhillstudios.molehill.log-util]
        [com.marzhillstudios.molehill.config :only [*site-config* with-config]]
        [clojure.contrib.duck-streams :only [file-str]]))

; TODO(jwall): Unit-Tests
(defn is-clj-file?
  {:tab Boolean}
  [filename]
  (= (take-last 3 filename) (seq "clj")))

(defn prompt
  ([] (prompt "?"))
  ([msg]
     (print msg)
     (read-line)))

; TODO(jwall): Unit-Tests
(defn is-content-file?
  {:tag Boolean}
  ([filename] (is-content-file? *site-config* filename))
  ([config filename]
  (and (= (dirname (path-str (normalize-relative-path filename)))
          (:site-content-dir config))
       (not (is-clj-file? filename)))))

(defn dir-exists? [dir]
  (cond
    (and (.exists dir)
         (.isDirectory dir))
      true
    :else
      false))

(defn- site-inited-?
  {:tag Boolean}
  ([] (site-inited-? *site-config*))
  ([config]
     (let [index-dir (file-str (:site-index-dir config))
           template-dir (file-str (:site-template-dir config))
           root-dir (file-str (:site-root config))
           content-dir (file-str (:site-content-dir config))
           entry-dir (file-str root-dir "/entries")
           hg-dir (file-str ".hg")]
       (reduce #(and %1 (dir-exists? %2)) true
               [root-dir
                entry-dir
                content-dir
                index-dir
                template-dir
                hg-dir]))))

(def site-inited?
     (memoize site-inited-?))

(defn distinctp
  "Returns a lazy sequence of the elements of coll with duplicates removed"
  [pred coll]
    (let [step (fn step [xs seen]
                   (lazy-seq
                    ((fn [[f :as xs] seen]
                      (when-let [s (seq xs)]
                        (if (contains? seen (pred f)) 
                          (recur (rest s) seen)
                          (cons f (step (rest s) (conj seen (pred f)))))))
                     xs seen)))]
      (step coll #{})))
